package org.spring.blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;

import java.util.Date;
import java.util.Map;

@Data
public class JWTUtil {

    //盐值
    private static String key = "1427481736@qq.com";

    private static long ttl = 2 * LRConstants.TimeValue.hour_ms;//2个小时


    /**
     * @param claims 载荷内容
     * @param ttl    有效时长
     * @return 加密内容
     */
    public static String createToken(Map<String, Object> claims, long ttl) {
        JWTUtil.ttl = ttl;
        return createToken(claims);
    }


    public static String createRefreshToken(String userId, long ttl) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(userId)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key);
        if (ttl > 0) {
            builder.setExpiration(new Date(nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * @param claims 载荷
     * @return token
     */
    private static String createToken(Map<String, Object> claims) {

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder()
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key);

        if (claims != null) {
            builder.setClaims(claims);
        }

        if (ttl > 0) {
            builder.setExpiration(new Date(nowMillis + ttl));
        }
        return builder.compact();
    }

    public static Claims parseJWT(String jwtStr) {
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }

    public static String createJwt(String _id, String _subject, Map<String, Object> _claims, long _ttl) {
        ttl = _ttl;

        return createJwt(_id, _subject, _claims);
    }

    public static String createJwt(String _id, String _subject, Map<String, Object> _claims) {
        long timeMillis = System.currentTimeMillis();

        Date date = new Date(timeMillis);

        JwtBuilder builder = Jwts.builder().setId(_id)
                .setSubject(_subject)
                .setIssuedAt(date)
                .signWith(SignatureAlgorithm.HS256, key);

        if (_claims != null) {
            builder.setClaims(_claims);
        }

        if (ttl > 0) {
            // 设置时间限制
            builder.setExpiration(new Date(timeMillis + ttl));
        }

        return builder.compact();
    }
}
